﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;


namespace Nirvana
{
    /// <summary>
    /// lua代码使用，代替InputField 的KeyCode 手动指定回调事件功能
    /// </summary>
    [AddComponentMenu("Nirvana/UI/Bind/Event Bind InputField KeyCode")]
    [RequireComponent(typeof(InputField))]
    public class UIEventBindInputFieldKey : UIEventBind
    {
        [Serializable]
        private class InputKeyBindEvent
        {
            [EventName]
            [SerializeField]
            private string eventName;

            [SerializeField]
            private KeyCode keyCode;

            private SignalEvent _signalevent;

            public void Init(UIEventBind bind)
            {
                this._signalevent = bind.GetSignalEvent(this.eventName);
                if (this._signalevent == null)
                {
                    Debug.LogWarning("Can not find event: " + this.eventName);
                }
            }

            public void Excute()
            {
                if (Input.GetKeyUp(this.keyCode) && this._signalevent != null)
                {
                    this._signalevent.Excute();
                }
            }
        }

        [SerializeField]
        private InputKeyBindEvent[] keyEvents;
        private InputField _input;

        protected override void Awake()
        {
            base.Awake();
            this._input = base.GetComponent<InputField>();
            if (this.keyEvents != null)
            {
                foreach (var k in this.keyEvents)
                {
                    k.Init(this);
                }
            }
        }

        protected override void RefreshBind()
        {
            if (this.keyEvents != null)
            {
                foreach (var k in this.keyEvents)
                {
                    k.Init(this);
                }
            }
        }

        void Update()
        {
            if (this._input.isFocused)
            {
                foreach (var k in this.keyEvents)
                {
                    k.Excute();
                }
            }
        }

    }

}

